<?php

	// We need access to the database
	require_once('scripts/dbconnection.php');

	// Get the type we are working on
	$type = $_REQUEST["type"];

	if ($type == "author")
	{
		/* Adding an author */
		
		// Check if we need to add an author
		if ($_REQUEST["action"] == "new")
		{
			// We need to add the provide author/authors

			// Connect to the database
			require_once('scripts/dbconnection.php');

			// Are we adding a new author
			if ($_POST["action"] == "new")
			{
				// Get the authorName
				$authorName = $_POST["newAuthor"];

				// Make sure the user doesn't enter a blank author name
				if (strlen($authorName) < 1)
				{
					exit("Error: You must enter an author name to add it!");
				}

				// Make sure the author isn't already in the database
				$result = mysql_query("SELECT * FROM AUTHOR WHERE AuthorName = '" . $authorName . "'");

				// This should be 0
				if (mysql_num_rows($result) != 0)
				{
					exit("Error: The author already exists in the database!");
				}

				// Add the author to the database
				$result = mysql_query("INSERT INTO AUTHOR VALUES(NULL, '" . $authorName . "')");
				
				// Go back to the add author page
				if (isset($_POST["redirect"]))
				{
					header("Location: author_add.php");
				}
			}
		}
		else if ($_REQUEST["action"] == "remove")
		{
			// Get the ID number of the author to remove
			$id = $_REQUEST["id"];
			
			// Remove the author from all the books
			mysql_query("UPDATE BOOK SET AuthorID = NULL WHERE AuthorID = " . $id);
			
			// Check for errors
			if (mysql_error() != '')
				exit("Error: " . mysql_error());
			
			// Remove the author
			mysql_query("DELETE FROM AUTHOR WHERE AuthorID = " . $id);
			
			// Check for errors
			if (mysql_error() != '')
				exit("Error: " . mysql_error());
			
			// All Done
			echo "The author has been removed.";
		}
	}

?>